#!/usr/bin/perl
#
#	$HeadURL$
#	$Revision$
#	$Date$
#

use strict;
use warnings;

use IO::Socket::INET;
#use Digest::SHA qw(sha256_hex);
use Digest::MD5 qw(md5_hex);
use Time::HiRes qw(gettimeofday);

#	This is CLI tool, thus we require arguments.
unless (@ARGV && $ARGV[3]) {
	print "Usage: $0 <host> <port> <action> <password> [detail]\n";
	print "\taction - get/toggle/set\n";
	print "\tnote, set action requires a 5th parameter, the details of the status\n";
	exit 1;
}

#	Running configuration;
my $host = $ARGV[0] || '127.0.0.1';
my $port = $ARGV[1] || 5000;
my $user = 'user';
my $action = $ARGV[2];
my $password = $ARGV[3] || 'password';
my $detail = $ARGV[4] || '';

my $socket = new IO::Socket::INET (
	PeerHost => $host,
	PeerPort => $port,
	Proto => 'tcp',
) or die "ERROR in Socket Creation : $!\n";
$socket->autoflush(1);

print "TCP Connection Success: $host $port\n";

#	Request the nonce.
print "Requesting nonce... ";
print $socket "REQ_NONCE\n";

#	Receive the nonce.
my $nonce = undef;
$socket->recv($nonce,1024);
chomp $nonce;

if ($nonce =~ /^NONCE ([a-f0-9]+)$/) {
	print "$nonce\n";
	$nonce = $1;
} else {
	print "Problem, sensor would not provide nonce.\n";
	exit;
}

#	Build our nonce, encode authentication, then request status.
print "Requesting status... ";
my $cnonce = join '', gettimeofday();
my $auth_hash = md5_hex($nonce.$cnonce.$password);
#my $auth_hash = sha256_hex($nonce.$cnonce.$password);

#	Take our selected action.
if ($action =~ /^get$/i) {

	print "REQ_STATUS user $cnonce $auth_hash\n";
	print $socket "REQ_STATUS user $cnonce $auth_hash\n";

} elsif (($action =~ /^set$/i) && $detail) {
	print "SET_STATUS($detail) user $cnonce $auth_hash\n";
	print $socket "SET_STATUS($detail) user $cnonce $auth_hash\n";

} elsif ($action =~ /^toggle$/i) {

	print "TOGGLE_STATUS user $cnonce $auth_hash\n";
	print $socket "TOGGLE_STATUS user $cnonce $auth_hash\n";

} else {
	print "Not a valid action.\n";
}

#	Receive the response, the actual status message, why we're here, etc.
my $response = undef;
$socket->recv($response,1024);
chomp $response;

if ($response =~ /^STATUS (.*)$/) {
	$response = $1;
	print "$response\n";
	print "SENSOR $host:$port $response\n";
} else {
	print "Problem, invalid response.\n";
}

#	Not strictly necessary, but a little more polite than just exiting.
print $socket "QUIT\n";
$socket->close();
exit;

# EOF
